import React, { Component } from 'react'
// 受控组件 value、checked / onChange

class App extends Component {
  state = {
    count: 100,
    // 单个复选框
    all: false,
    // 多个复选框
    lessons: ['html', 'css', 'js', 'vue', 'react'],
    selectedLesson: []
  }

  selectHandle = (value) => (e) => {
    // console.log(value, e.target.checked)
    if (e.target.checked) {
      this.setState((state) => ({
        selectedLesson: [...state.selectedLesson, value]
      }))
    } else {
      this.setState((state) => ({
        selectedLesson: state.selectedLesson.filter((item) => item != value)
      }))
    }
  }

  selectAllHandle = (e) => {
    let selectedLesson = []
    if (e.target.checked) {
      selectedLesson = this.state.lessons
    } else {
      selectedLesson = []
    }
    this.setState({ all: e.target.checked, selectedLesson })
  }

  render() {
    return (
      <div>
        <div>
          <input
            type="checkbox"
            checked={this.state.all}
            onChange={this.selectAllHandle}
          />
        </div>
        <div>
          <ul>
            {this.state.lessons.map((item, index) => (
              <li key={index}>
                <span>
                  <input
                    type="checkbox"
                    value={item}
                    checked={this.state.selectedLesson.includes(item)}
                    onChange={this.selectHandle(item)}
                  />
                </span>
                <span>{item}</span>
              </li>
            ))}
          </ul>
        </div>
      </div>
    )
  }
}

export default App
